//
//  OAuthViewController.swift
//  weibo
//
//  Created by 张宏芝 on 15/9/1.
//  Copyright © 2015年 kama. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController,UIWebViewDelegate {

    
    private lazy var webView = UIWebView()
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    
    override func loadView() {
//        根视图是webView
        view = webView
        webView.delegate = self
        
        title = "登陆新浪微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
    }
    
   @objc private func close(){
    SVProgressHUD.dismiss()
    dismissViewControllerAnimated(true, completion: nil)
    
    }
    
   @objc private func autoFill(){
//    自动填充js
    let js = "document.getElementById('userId').value = 'zhz2015kama@sina.com';" +
    "document.getElementById('passwd').value = '510430';"
    webView.stringByEvaluatingJavaScriptFromString(js)
    
    }
    
    override func viewDidLoad() {
        webView.loadRequest(NSURLRequest(URL:NetWorkTools.sharedTools.oauthUrl))
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString

//        1.判断request.url的前半部分是不是回调地址,如果不是回调地址,继续加载
        if !urlString.hasPrefix(NetWorkTools.sharedTools.redirectUri){
            return true
        }
        
//        2.判断如果是回调地址,检查query的查询字符串,判断是否包含"code = "
//        query就是URL中?后边的全部内容
        if let query = request.URL!.query where query.hasPrefix("code="){
            
//        3.如果有,获取code
            let code = query.substringFromIndex("code=".endIndex)
            print(code)
            
//        4.调用获取网络的方法,获取token
           UserAccountViewModel.sharedUserAccount.loadUserAccount(code).subscribeError({ (error) -> Void in
            
            printLog(error)
            
            }, completed: { () -> Void in
                printLog("登陆成功!!")
//                关闭控制器
                SVProgressHUD.dismiss()
                
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    
                    NSNotificationCenter.defaultCenter().postNotificationName(HMSwitchRootViewControllerNotification, object: "Main")
                })
           })
            
        }else{
            printLog("取消")
        }
        return false
    }
}
